'''
Created on 31.12.2012

@author: B. Wilbertz
'''

import os.path, logging
    
w1path = "/sys/bus/w1/devices"


class DS18B20():
    '''
    Class for accessing the a DS18B20 temperature sensor
    using the Linux kernel's 1-wire bus implementation. 
    '''

    sensor_path = ""
    OK = False
    
    def __init__(self, w1Id):
        if not os.path.exists(w1path):
            logging.error("1-wire bus not found")
            return
        
        self.sensor_path = os.path.join(w1path, "28-" + w1Id)
        
        if not os.path.exists(self.sensor_path):
            logging.error("Sensor %s not found" % (w1Id))
            return
    
        self.OK = True    
        # print self.sensor_path
    
    def getTemp(self):
        if not self.OK:
            logging.fatal("1-wire device was not properly initialized!")
            return
    
        f = open(self.sensor_path + '/w1_slave', 'r')
        tString = f.read()
        f.close()
        
        logging.debug("DS18B20: " + tString)
        
        if tString.find("NO") >= 0:
            logging.warn("Wrong CRC in 1-wire response")
            return
        
        if tString.find("t=85000") >= 0:
            logging.info("Dropping DS18B20 power-on reset temperature value of 85C.")
            return
        
        p = tString.find("t=")
        return float(tString[p + 2:-1]) / 1000


